package wsz.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import wsz.io.Resource;
import wsz.pojo.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * 读取并解析xml
 * @author wsz
 * @date 2021/10/1 0:54
 **/
public class XmlConfigBuilder {

    private Configuration configuration;

    public XmlConfigBuilder () {
        this.configuration = new Configuration();
    }
    /**
     * 使用dom4j
     * @param inputStream
     * @return
     */
    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException {
        Document document = new SAXReader().read(inputStream);

        // 解析sqlMapConfig.xml
        Element rootElement = document.getRootElement();
        List<Element> list = rootElement.selectNodes("//property");
        Properties properties = new Properties();
        for (Element el : list) {
            String name = el.attributeValue("name");
            String value = el.attributeValue("value");
            properties.setProperty(name, value);
        }

        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);

        // 解析mapper.xml
        List<Element> mapperList = rootElement.selectNodes("//mapper");
        for (Element el : mapperList) {
            String mapperPath = el.attributeValue("resource");
            InputStream resource = Resource.getResourceAsStream(mapperPath);
            XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
            mapperBuilder.parseMapper(resource);
        }

        return configuration;
    }
}
